<template>
	<div style="width: 100%">
		<Menu></Menu>
		<div class="table-admin-container" style="margin-top: 2px; display: flex; padding: 10px; margin-bottom: 80px">
			<el-row :gutter="10" style="width: 100%">
				<el-col :span="4">
					<el-card style="height: 100%">
						<List :hasAll="true" @changeChain="changeChain"></List>
					</el-card>
				</el-col>
				<el-col :span="20" style="height: 100%">
					<TableSearch :search="state.tableData.search" @search="onSearch" />

					<div style="width: 100%; background-color: #fff; padding: 10px; font-size: 16px">
						<div class="flex label_div">
							<div class="label_name">省份地区:</div>
							<div class="flex_ac flex_w">
								<div class="label_item" v-for="(i, k) in qu_id?quList:shi_id?quList:sheng_id?shiList:cityList" :key="k"
								@click="qu_id?changeQu(i):shi_id?changeQu(i):sheng_id?changeShi(i):changeSheng(i)">
									{{ i.city_name }}
								</div>
							</div>
						</div>
						<div class="flex label_div">
							<div class="label_name">所属行业:</div>
							<div class="flex_ac flex_w">
								<div class="label_item" v-for="(i, k) in industryList" :key="k">
									<el-popover :offset="0" :show-arrow="false" placement="bottom-start" width="auto" trigger="hover">
										<template #reference>
											<el-checkbox
												:indeterminate="industryCheck[k].isIndeterminate"
												@change="(val) => CheckAllChange(val, k)"
												v-model="industryCheck[k].checkAll"
												>{{ i.industry_name }}</el-checkbox
											>
										</template>
										<div class="list_div" style="max-height: 10rem">
											<el-checkbox-group v-model="industryCheck[k].list" @change="(val) => ChangeCheckIndustry(val, k)">
												<div class="flex_col">
													<el-checkbox v-for="i1 in i.children" :key="i1.id" :label="i1.id" :value="i1.id">
														<div class="text_line" style="width: 10rem">{{ i1.industry_name }}</div>
													</el-checkbox>
												</div>
											</el-checkbox-group>
										</div>
									</el-popover>
								</div>
							</div>
						</div>

						<div class="flex_ac label_div" v-for="(i, k) in labelList" :key="k">
							<div class="label_name">{{ i.name }}:</div>
							<div class="flex_ac">
								<div class="label_item" v-for="(i1, k1) in i.labels" :key="k1" @click="changeLabel(i1)">
									{{ i1.label }}
								</div>
							</div>
						</div>
						<div class="choose_div flex_ac" v-if="qu_id||shi_id||sheng_id|| labelItems.length > 0 || industryItems.length > 0">
							<div class="label_name">已选条件:</div>
							<div class="flex_w pl20">
								<el-tag v-if="sheng_id" class="choose_item" closable type="primary" @close="delSheng()">{{ sheng_name }}</el-tag>
								<el-tag v-if="shi_id" class="choose_item" closable type="primary" @close="delShi()">{{ shi_name }}</el-tag>
								<el-tag v-if="qu_id" class="choose_item" closable type="primary" @close="delQu()">{{ qu_name }}</el-tag>
								<el-tag v-if="industryItems.length > 0" effect="plain" class="choose_item" closable type="success" @close="delIndust()">
									<span style="color: #999">行业：</span>
									<el-tooltip class="box-item" effect="dark" :content="industryItems.map((i) => i.industry_name).join(',')" placement="top">
										<span class="text_line" style="position: relative; top: 1px; max-width: 15rem; display: inline-block">{{
											industryItems.map((i) => i.industry_name).join(',')
										}}</span>
									</el-tooltip>
								</el-tag>
								<el-tag v-if="labelItems.length > 0" effect="plain" class="choose_item" closable type="primary" @close="delLabel()">
									<span style="color: #999">标签：</span>
									<el-tooltip class="box-item" effect="dark" :content="labelItems.map((i) => i.label).join(',')" placement="top">
										<span class="text_line" style="position: relative; top: 1px; max-width: 15rem; display: inline-block">{{
											labelItems.map((i) => i.label).join(',')
										}}</span>
									</el-tooltip>
								</el-tag>
							</div>
						</div>
					</div>
					<Table
						ref="tableRef"
						v-bind="state.tableData"
						class="table-admin"
						@updateRow="onTableUpdateRow"
						style="height: 100%"
						@add="onTableAddRow"
						@delRow="onTableDelRow"
						@batchDel="onTableBatchDel"
						@pageChange="onTablePageChange"
						@sortHeader="onSortHeader"
					/>
					<EditDialog ref="editRef" @refresh="getTableData()" />
				</el-col>
			</el-row>
		</div>
		<!-- <div  class="table-admin-container  layout-padding"  style="width: 400px; float: left; height: 96%;  top: 50px; ">-->
	</div>
</template>

<script setup lang="ts" name="cgjudgeLists">
import { defineAsyncComponent, reactive, ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { getList, getLabelList, getIndustryList } from '/@/api/com/index';

// , del, batDel
// 引入组件
const List = defineAsyncComponent(() => import('/@/views/cogen/cgjudge/List.vue'));
const Menu = defineAsyncComponent(() => import('/@/views/cogen/cgjudge/menu.vue'));
const Table = defineAsyncComponent(() => import('/@/components/table/index.vue'));
const TableSearch = defineAsyncComponent(() => import('/@/components/table/search.vue'));
const EditDialog = defineAsyncComponent(() => import('/@/views/cogen/cgjudge/form/edit.vue'));

const cityList = ref(JSON.parse(sessionStorage.quanCity)[0].children);
const qu_id = ref('')
const shi_id = ref('')
const sheng_id = ref('')
const qu_name = ref('')
const shi_name = ref('')
const sheng_name = ref('')
const quList = ref([])
const shiList = ref([])

const changeQu = (i) => {
	qu_id.value = i.id
	qu_name.value = i.city_name
	changeCity()
}
const changeShi = (i) => {
	shi_id.value = i.id
	shi_name.value = i.city_name
	quList.value = shiList.value.find(i1 => i1.id == i.id).children
	changeCity()
}
const changeSheng = (i) => {
	sheng_id.value = i.id
	sheng_name.value = i.city_name
	shiList.value = cityList.value.find(i1 => i1.id == i.id).children
	changeCity()
}

const delQu = ()=>{
	qu_id.value = ''
	qu_name.value = ''
	changeCity();
}
const delShi = ()=>{
	shi_id.value = ''
	shi_name.value = ''
	quList.value = []
	delQu();
}
const delSheng = ()=>{
	sheng_id.value = ''
	sheng_name.value = ''
	shiList.value = []
	delShi();
}

const changeCity = () => {
	state.tableData.param.city_id = qu_id.value || shi_id.value || sheng_id.value
	tableRef.value.pageReset();
};

const changeChain = (chain) => {
	state.tableData.param.chain_id = chain.id
	tableRef.value.pageReset();
}

// 定义变量内容
const tableRef = ref<RefType>();

const labelList = ref([]);
const industryList = ref([]);
const industryCheck = ref([]);
const industryItems = ref([]);

onMounted(() => {
	getLabelList().then((res) => {
		labelList.value = res.data;
	});
	getIndustryList().then((res) => {
		for (let i = 0; i < res.data.length; i++) {
			industryCheck.value.push({ checkAll: false, isIndeterminate: false, list: [] });
		}
		industryList.value = res.data;
	});
	getTableData();
});

const CheckAllChange = (val, k) => {
	industryCheck.value[k].list = val ? industryList.value[k].children.map((i) => i.id) : [];
	industryCheck.value[k].isIndeterminate = false;
	changeIndust();
};
const ChangeCheckIndustry = (val, k) => {
	const checkedCount = val.length;
	industryCheck.value[k].checkAll = checkedCount === industryList.value[k].children.length;
	industryCheck.value[k].isIndeterminate = checkedCount > 0 && checkedCount < industryList.value[k].children.length;
	changeIndust();
};

const changeIndust = () => {
	let ids = [];
	industryItems.value = [];
	industryCheck.value.forEach((i, k) => {
		ids.push(...i.list);
		if (i.checkAll) {
			industryItems.value.push({ industry_name: industryList.value[k].industry_name });
		} else {
			i.list.forEach((x) => {
				let item = industryList.value[k].children.find((x1) => x1.id == x);
				industryItems.value.push(item);
			});
		}
	});
	state.tableData.param.industry_ids = ids.join(',');
	tableRef.value.pageReset();
};

const state = reactive<TableDemoState>({
	tableData: {
		// 列表数据（必传）
		data: [],
		// 表头内容（必传，注意格式）
		header: [
			{ key: 'company_name', colWidth: '300', title: '企业名称', type: 'text', isCheck: true },
			{ key: 'chain_name', colWidth: '300', title: '所属产业', type: 'list', isCheck: true },
			{ key: 'legal', colWidth: '80', title: '法人', type: 'text', isCheck: true },
			{ key: 'elephone', colWidth: '100', title: '联系电话', type: 'text', isCheck: true },
			{ key: 'score', colWidth: '80', title: '评分', type: 'text', isCheck: true },
		],
		// 配置项（必传）
		config: {
			total: 0, // 列表总数
			loading: false, // loading 加载
			isButton: true,
			isBorder: false, // 是否显示表格边框
			isSerialNo: true, // 是否显示表格序号
			isSelection: true, // 是否显示表格多选
			isOperate: true, // 是否显示表格操作栏
			isOperate: true, // 是否显示表格操作栏
			isCollect: 'admin:chain:invest',
			isExport: 'admin:chain:invest',
			isSee: 'admin:chain:invest',
		},
		// 搜索表单，动态生成（传空数组时，将不显示搜索，注意格式）
		search: [
			{ label: '关键词', prop: 'keywords', placeholder: '请输入关键词', required: false, type: 'input' },
		],
		// 搜索参数（不用传，用于分页、搜索时传给后台的值，`getTableData` 中使用）
		param: {
			page: 1,
			psize: 10,
			label_ids: '',
			industry_ids: '',
			chain_id:''
		},
		//显示分页
		showpage: 1,
		// 打印标题
		printName: '数据打印',
		//列字典
		dictData: {},
	},
});

// // 初始化列表数据
const getTableData = () => {
	state.tableData.config.loading = true;
	state.tableData.data = [];
	getList(state.tableData.param).then((response: any) => {
		state.tableData.data = response.data.code.data;
		state.tableData.config.total = response.data.code.total;
		state.tableData.config.loading = false;
	});
};

const labelItems = ref([]);
const changeLabel = (val) => {
	if (labelItems.value.findIndex((x) => x.id == val.id) > -1) {
		return;
	} else {
		labelItems.value.push(val);
		state.tableData.param.label_ids = labelItems.value.map((i) => i.id).join(',');
		tableRef.value.pageReset();
	}
};
const delLabel = () => {
	labelItems.value.length = 0;
	state.tableData.param.label_ids = '';
	// labelItems.value.splice(index, 1);
	// state.tableData.param.label_ids = labelItems.value.map((i) => i.id).join(',');
	tableRef.value.pageReset();
};
const delIndust = () => {
	industryCheck.value.forEach((i) => {
		i.checkAll = false;
		i.isIndeterminate = false;
		i.list = [];
	});
	changeIndust();
};

// 搜索点击时表单回调
const onSearch = (data: EmptyObjectType) => {
	state.tableData.param = Object.assign({}, state.tableData.param, { ...data });
	tableRef.value.pageReset();
};
// 删除当前项回调
const onTableDelRow = (row: EmptyObjectType) => {
	return del(row.id).then(() => {
		getTableData();
		ElMessage.success(`删除法官${row.name}成功！`);
	});
};
const onTableBatchDel = (ids: string) => {
	return batDel(ids).then(() => {
		getTableData();
		ElMessage.success(`批量删除成功！`);
	});
};
// 分页改变时回调
const onTablePageChange = (page: TableDemoPageType) => {
	state.tableData.param.page = page.page;
	state.tableData.param.psize = page.psize;
	getTableData();
};
// 拖动显示列排序回调
const onSortHeader = (data: TableHeaderType[]) => {
	state.tableData.header = data;
};

/** 新增按钮操作 */
const onTableAddRow = () => {
	editRef.value.openDialog('add');
};
/** 修改按钮操作 */
const onTableUpdateRow = (row: any) => {
	editRef.value.openDialog('edit', row);
};
</script>

<style scoped lang="scss">
.menu {
	width: 100%;
	height: 50px;
	background-color: #ffffff;
	li {
		list-style: none;
		float: left;
		width: 5.8%;
		font-size: 14px;
		line-height: 38px;
		text-align: center;
		padding-bottom: 7px;
		.el-link {
			color: #000000 !important;
		}
		.el-link:hover {
			font-size: 16px;
			color: #1890ff !important;
			border-bottom: #1890ff 3px solid;
			border-radius: 1px 2px 2px 1px;
		}
		.active {
			font-size: 16px;
			color: #1890ff !important;
			border-bottom: #1890ff 3px solid;
			border-radius: 1px 2px 2px 1px;
		}
	}
}
.table-admin-container {
	.table-admin-padding {
		padding: 15px;
		.table-admin {
			flex: 1;
			overflow: hidden;
		}
	}
}
.cl {
	clear: both;
}

.label_div {
	line-height: 30px;
	margin-top: 15px;
	&::v-deep .el-checkbox {
		height: 20px !important;
		color: #000 !important;
		font-size: 16px !important;
	}
}
.label_name {
	color: #666;
	font-size: 16px;
	margin-left: 10px;
}
.label_item {
	margin-left: 20px;
	color: #000;
	font-size: 16px;
	cursor: pointer;
}

.choose_div {
	border-top: 1px solid #eee;
	min-height: 50px;
	margin-top: 10px;
	.label_name {
		color: #333;
		font-size: 15px;
		margin-left: 10px;
		font-weight: 800;
	}
}
.choose_item {
	margin: 5px 0;
	margin-right: 10px;
	cursor: pointer;
}
</style>
